﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace Charming.Showcase
{
    public partial class SearchResults : PhoneApplicationPage
    {
        private string query;

        public SearchResults()
        {
            InitializeComponent();
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            InTheHand.ApplicationModel.DataTransfer.DataTransferManager.GetForCurrentView().DataRequested -= DataRequested;
            base.OnNavigatingFrom(e);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.query = NavigationContext.QueryString["queryText"];
            Results.Text = "you searched for \"" + query + "\"";
            InTheHand.ApplicationModel.DataTransfer.DataTransferManager.GetForCurrentView().DataRequested += DataRequested;

            ResultList.ItemsSource = App.samplePhrases.Where<string>(ContainsQuery);
            base.OnNavigatedTo(e);
        }

        private bool ContainsQuery(string value)
        {
            return value.Contains(query);
        }

        private void ShareButton_Click(object sender, EventArgs e)
        {
            InTheHand.ApplicationModel.DataTransfer.DataTransferManager.ShowShareUI();
        }

        void DataRequested(InTheHand.ApplicationModel.DataTransfer.DataTransferManager sender, InTheHand.ApplicationModel.DataTransfer.DataRequestedEventArgs args)
        {
            InTheHand.ApplicationModel.DataTransfer.DataPackage dp = args.Request.Data;
            //dp.Properties.Title = "Charmer.Showcase";
            //dp.Properties.Description = "An example share implementation";
            if (ResultList.SelectedIndex > -1)
            {
                dp.SetText(ResultList.SelectedItem.ToString());
            }
            else
            {
                dp.SetText(query);
            }
        }

        private void ResultList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}